package com.demo.apparel.service.uniapp.Impl;

import com.demo.apparel.entity.ClothesType;
import com.demo.apparel.dto.ClothesUploadDTO;
import com.demo.apparel.entity.Clothes;
import com.demo.apparel.mapper.uniapp.WxClothesTypeMapper;
import com.demo.apparel.mapper.uniapp.WxClothesMapper;
import com.demo.apparel.service.uniapp.WxClothesService;
import com.demo.apparel.vo.uniapp.ClothesDetailVO;
import com.demo.apparel.vo.uniapp.SimpleClothesVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class WxClothesServiceImpl implements WxClothesService {

    @Autowired
    private WxClothesMapper wxClothesMapper;

    @Autowired
    private WxClothesTypeMapper wxClothesTypeMapper;


    private final String uploadDir = System.getProperty("user.dir") + "/uploads/";
    private final String urlPrefix = "/static/image/";

    /**
     *
     * @param file
     * @param userId
     * @return
     */
    @Override
    public Map<String, String> uploadImageAndSave(MultipartFile file, String userId) {
        if (file == null || file.isEmpty()) {
            throw new RuntimeException("文件为空");
        }

        File dir = new File(uploadDir);
        if (!dir.exists()) dir.mkdirs();

        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename != null && originalFilename.contains(".")
                ? originalFilename.substring(originalFilename.lastIndexOf("."))
                : "";

        String filename = UUID.randomUUID().toString().replace("-", "") + suffix;
        String imageUrl = urlPrefix + filename;
        String clothesId = UUID.randomUUID().toString().replace("-", "");

        try {
            file.transferTo(new File(dir, filename));

            // 写入数据库（初始只插入 image_url、userId、id）
            Clothes clothes = new Clothes();
            clothes.setId(clothesId);
            clothes.setUserId(userId);
            clothes.setImageUrl(imageUrl);
            clothes.setStatusSale("0");
            clothes.setUpdateTime(LocalDateTime.now());

            wxClothesMapper.insert(clothes);

            Map<String, String> result = new HashMap<>();
            result.put("id", clothesId);
            result.put("imageUrl", imageUrl);
            return result;

        } catch (IOException e) {
            throw new RuntimeException("图片上传失败", e);
        }
    }

    /**
     *
     * @param dto
     * @param userId
     */

    @Override
    public void saveClothesInfo(ClothesUploadDTO dto, String userId) {
        Clothes clothes = wxClothesMapper.selectById(dto.getId());
        if (clothes == null || !Objects.equals(clothes.getUserId(), userId)) {
            throw new RuntimeException("无效的衣服ID");
        }

        System.out.println("收到请求参数：name=" + dto.getName() + ", category=" + dto.getCategory());

        Integer dtoCategory = dto.getCategory() instanceof Integer ? (Integer) dto.getCategory() : Integer.valueOf(dto.getCategory().toString());

        // 先更新category字段为前端传入的
        clothes.setCategory(dtoCategory);

        // 根据传入的category去匹配type_name
        List<ClothesType> typeList = wxClothesTypeMapper.selectByCategory(dtoCategory);

        String matchedTypeName = null;
        for (ClothesType type : typeList) {
            String keywordsStr = type.getKeywords();
            if (keywordsStr == null || dto.getName() == null) continue;

            String[] keywords = keywordsStr.replace("\"", "").split(",");
            System.out.println("尝试匹配类型：" + type.getTypeName() + "，关键词：" + Arrays.toString(keywords));

            for (String keyword : keywords) {
                if (dto.getName().contains(keyword.trim())) {
                    matchedTypeName = type.getTypeName();
                    System.out.println("匹配成功！关键词：" + keyword + " -> 类型：" + matchedTypeName);
                    break;
                }
            }

            if (matchedTypeName != null) break;
        }

        // 如果没匹配成功，随便用第一个type的typeName作为默认值
        if (matchedTypeName == null && !typeList.isEmpty()) {
            matchedTypeName = typeList.get(0).getTypeName();
            System.out.println("没有匹配成功，默认使用第一个类型：" + matchedTypeName);
        }
        clothes.setName(matchedTypeName != null ? matchedTypeName : dto.getName());
        clothes.setDescription(dto.getDescription());
        clothes.setSeason(dto.getSeason());
        clothes.setUpdateTime(LocalDateTime.now());

        wxClothesMapper.updateById(clothes);
        System.out.println("衣服信息更新成功！");
    }

    @Override
    public List<SimpleClothesVO> searchUserClothes(String userId, String keyword, String season) {
        List<String> categoryList = wxClothesTypeMapper.findCategoriesByKeyword(keyword);
        List<Clothes> list = wxClothesMapper.searchClothesByEnhancedKeyword(userId, keyword, season, categoryList);
        return convertToVO(list);
    }

    private List<SimpleClothesVO> convertToVO(List<Clothes> list) {
        return list.stream().map(item -> {
            SimpleClothesVO vo = new SimpleClothesVO();
            vo.setId(item.getId());
            vo.setImage(item.getImageUrl());
            vo.setDescription(item.getDescription());
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public ClothesDetailVO getClothesDetailById(String clothesId, String userId) {
        Clothes clothes = wxClothesMapper.selectById(clothesId);
        if (clothes == null || !clothes.getUserId().equals(userId)) {
            throw new RuntimeException("衣物不存在或无权限查看");
        }

        ClothesDetailVO vo = new ClothesDetailVO();
        vo.setId(clothes.getId());
        vo.setName(clothes.getName());
        vo.setDescription(clothes.getDescription());
        vo.setCategory(String.valueOf(clothes.getCategory()));
        vo.setImageUrl(clothes.getImageUrl());
        vo.setStatusSale(clothes.getStatusSale());
        vo.setSeason(clothes.getSeason());
        vo.setUpdateTime(clothes.getUpdateTime());
        return vo;
    }

}

